#include "common.h"
#include "lwrb.h"
#include "FreeRTOS.h"
#include "task.h"
#include "stream_buffer.h"
#include "bsp_usart.h"

static void dmaIndexOffsetStore(struct dma_store_info_t *info, struct dma_recv_instance *instance)
{
    uint32_t last, new;
    last = instance->index_offset;
    new = LDMA->CH[instance->ch].DST;
    instance->index_offset = new;
    //数据溢出后重新开始
    if(last > new)
    {
        info->map.index = last;
        info->map.lens = (uint32_t)instance->dma_buff + ( instance->dma_len) - last;
        info->map2.index = (uint32_t)instance->dma_buff;
        info->map2.lens = new - (uint32_t)instance->dma_buff;
    }
    else
    {
        info->map.index = last;
        info->map.lens = new - last;
        info->map2.index = 0;
        info->map2.lens = 0;
    }
}

int dmaMsgStore(struct dma_recv_instance *instance)
{
    int ret = 0;
    struct dma_store_info_t info;
    dmaIndexOffsetStore(&info, instance);
    if(info.map.lens)
    {
        ret = 1;
        lwrb_write(&instance->rb, (const char * )info.map.index, info.map.lens);
    }
    if(info.map2.lens)
    {
        lwrb_write(&instance->rb, (const char * )info.map2.index, info.map2.lens);
    }
    return ret;
}


void dma_usart_recv_instance_init(struct dma_recv_instance *instance, uint8_t *buff, int size, uint8_t *dma_buff, uint8_t dma_ch)
{
    lwrb_init(&instance->rb, buff, size);
    instance->dma_len = size;
    instance->dma_buff = dma_buff;
    instance->index_offset = (uint32_t )dma_buff;    //设置默认偏移量
    instance->ch = dma_ch;
}

void dma_usart_send_instance_init(struct dma_send_instance *instance, int buffer_size, int trigger_level, uint8_t dma_ch)
{
    instance->stream = xStreamBufferCreate(buffer_size, trigger_level);
    instance->ch = dma_ch;
    instance->transmit_status = IDLE;
}

